import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { RescueRecord } from '../../entities/RescueRecord.entity'

@Provide()
export class RescueRecordService {
  @InjectEntityModel(RescueRecord)
  repo!: Repository<RescueRecord>

  async list(page: number = 1, pageSize: number = 10) {
    const queryBuilder = this.repo.createQueryBuilder('rr')
      // 关联帮扶者（救助人）
      .leftJoin('rr.user', 'rescuer')
      // 关联救助信息
      .leftJoin('rr.rescueInfo', 'ri')
      // 关联救助信息中的儿童
      .leftJoin('ri.child', 'child')
      // 关联救助信息中的发起人（监护人）
      .leftJoin('ri.guardian', 'guardian')
      .select([
        'rr.id AS id',
        'rr.createTime AS createTime',
        'rr.userId AS userId',
        // 儿童信息
        'child.name AS childName',
        // 发起人（监护人）信息
        'guardian.id AS guardianId',
        'guardian.nickname AS guardianName',
        'guardian.phone AS guardianPhone',
        // 救助信息
        'ri.name AS rescueName',
        'ri.rescueStatus AS rescueStatus',
        'ri.rescueContent AS rescueContent',
        'ri.rescueImg AS rescueImg',
        // 帮扶者（救助人）信息
        'rescuer.id AS rescuerId',
        'rescuer.nickname AS rescuerName',
        'rescuer.phone AS rescuerPhone',
      ])
      .orderBy('rr.id', 'DESC');
    
    // 打印 SQL 用于调试
    console.log('SQL:', queryBuilder.getSql());
    
    // 获取总数
    const total = await queryBuilder.getCount();
    
    // 获取分页数据
    const items = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getRawMany();

    console.log('查询结果示例:', items[0]);

    return {
      total,
      items,
    }
  }

  async getById(id: number) {
    const result = await this.repo.createQueryBuilder('rr')
      // 关联帮扶者（救助人）
      .leftJoin('rr.user', 'rescuer')
      // 关联救助信息
      .leftJoin('rr.rescueInfo', 'ri')
      // 关联救助信息中的儿童
      .leftJoin('ri.child', 'child')
      // 关联救助信息中的发起人（监护人）
      .leftJoin('ri.guardian', 'guardian')
      .select([
        'rr.id AS id',
        'rr.createTime AS createTime',
        // 儿童信息
        'child.name AS childName',
        // 发起人（监护人）信息
        'guardian.nickname AS guardianName',
        'guardian.phone AS guardianPhone',
        // 救助信息
        'ri.name AS rescueName',
        'ri.rescueStatus AS rescueStatus',
        'ri.rescueContent AS rescueContent',
        'ri.rescueImg AS rescueImg',
        // 帮扶者（救助人）信息
        'rescuer.nickname AS rescuerName',
        'rescuer.phone AS rescuerPhone',
      ])
      .where('rr.id = :id', { id })
      .getRawOne();

    return result || null;
  }
}
